package hrhq.cntvcn.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;

import hrhq.cntvcn.mapper.HrhqImageMapper;
import hrhq.cntvcn.pojo.HrhqImage;
import hrhq.cntvcn.pojo.SearchResult;
import hrhq.cntvcn.service.SearchImageService;
import hrhq.cntvcn.utils.SolrUtils;

@Service
public class SearchImageServiceImpl implements SearchImageService {
	private static Logger logger = Logger.getLogger(SearchImageServiceImpl.class);
	private final static SolrClient solrClient = new SolrUtils().getZkSolrClient();
	@Autowired
	private HrhqImageMapper imageMapper;

	public void addIndexById(String... ids) {
		logger.info("执行添加索引操作");
		ArrayList<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();
		for (String id : ids) {
			HrhqImage image = imageMapper.selectImageById(id);
			SolrInputDocument document = new SolrInputDocument();
			document.addField("id", image.getId());	
			document.addField("image_title", image.getTitle());
			document.addField("image_online_date", image.getOnlineDate());	
			document.addField("image_modify_date", image.getModifyDate());
			document.addField("image_remark", image.getRemark());
			document.addField("image_click_num", image.getClickNum());
			document.addField("img_path1", image.getImgPath1());
			document.addField("image_group_id", image.getGroupId());
			docs.add(document);
		}
		try {
			solrClient.add(docs);
			solrClient.commit();
			logger.info("添加索引成功");
		} catch (SolrServerException e) {
			logger.error("Add docs Exception !!!\n" + e.getStackTrace() + "\n" + e.getCause());
			e.printStackTrace();
		} catch (IOException e) {
			logger.error("Unknowned Exception!!!!!\n" + e.getStackTrace() + "\n" + e.getCause());
			e.printStackTrace();
		}

	}

	public void deleteAllIndex() {
		logger.info("执行删除所有索引操作");
		try {
			solrClient.deleteByQuery("*:*");
			solrClient.commit();
			logger.info("删除索引成功");
		} catch (SolrServerException e) {
			logger.error("Delete Indexs Exception !!!\n" + e.getStackTrace() + "\n" + e.getCause());
			e.printStackTrace();
		} catch (IOException e) {
			logger.error("Unknowned Exception!!!!!\n" + e.getStackTrace() + "\n" + e.getCause());
			e.printStackTrace();
		}

	}

	public void deleteIndexByQuery(String query) throws SolrServerException, IOException {
		logger.info("执行删除索引操作");
		solrClient.deleteByQuery(query);
	}

	public SearchResult<HrhqImage> searchByImageTitle(String titleKey,Integer rows,Integer currPage) throws SolrServerException {
		logger.info("执行图集标题检索");
		// ApplicationContext context = new
		// ClassPathXmlApplicationContext("classpath:spring/applicationContext-*");
		// long start = System.currentTimeMillis();//测试时间11780ms
		// solrServer =(SolrServer) context.getBean("cloudSolrServer");
		// SearchResult<HrhqImage> searchByKey = searchByKey("_title", titleKey,
		// null,true);
		// long end = System.currentTimeMillis();
		// System.out.println(end-start);
		return searchByKey("image_title", titleKey, null, true,rows,currPage);
	}

	public SearchResult<HrhqImage> searchByImageRemark(String remarkKey,Integer rows,Integer currPage) throws SolrServerException {
		logger.info("执行图集摘要检索");
		return searchByKey("image_remark", remarkKey, null, true,rows,currPage);
	}

	public SearchResult<HrhqImage> searchByQuery(String DIYquery, Boolean isHighlight,Integer rows,Integer currPage) throws SolrServerException {
		logger.info("执行自定义检索");
		return searchByKey(null, null, DIYquery, isHighlight,rows,currPage);

	}

	public SearchResult<HrhqImage> searchByKey(String searchParam, String keywords, String DIYquery,
			Boolean isHighlight,Integer rows,Integer currPage) throws SolrServerException {
		SolrQuery query = new SolrQuery();
		if (DIYquery != null) {
			query.setQuery(DIYquery);
		} else {
			query.setQuery(searchParam + ":" + keywords);
		}
		query.setStart((currPage-1)*rows);
		query.setRows(rows);
		if (isHighlight == true) {
			query.setHighlight(true);
			query.addHighlightField(searchParam);
			query.setHighlightSimplePre("<font color=\"red\">");
			query.setHighlightSimplePost("</font>");
		}
		QueryResponse queryResponse = null;
		try {
			queryResponse = solrClient.query(query);
		} catch (IOException e) {
			e.printStackTrace();
		}
		SolrDocumentList results = queryResponse.getResults();
		Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();
		SearchResult<HrhqImage> searchResult = new SearchResult<HrhqImage>();
		List<HrhqImage> list = new ArrayList<>();
		for (SolrDocument doc : results) {
			HrhqImage image = new HrhqImage();
			// Image.setId((String) doc.get("id"));
			if (searchParam.equals("image_title")) {
				image.setTitle(highlighting.get(doc.get("id")).get(searchParam).get(0));
			} else {
				image.setTitle((String) doc.get("image_title"));
			}
			// Image.setTitle((String) doc.get("_title"));
			if (searchParam.equals("image_remark")) {
				image.setRemark(highlighting.get(doc.get("id")).get("searchParam").get(0));
			} else {
				image.setRemark((String) doc.get("image_remark"));
			}
			image.setClickNum((Integer) doc.get("image_click_num"));
			image.setGroupId((String) doc.get("image_group_id"));
			// System.out.println(list);
			list.add(image);
		}
		searchResult.setResultList(list);
		searchResult.setRecordCount(results.getNumFound());
		return searchResult;
	}

	/*
	 * 对CloudSolrServer单例注入 private static synchronized SolrServer
	 * getCloudSolrServer(final String zkHost) { if(solrServer == null) { try {
	 * solrServer = new CloudSolrServer(zkHost); }catch(Exception e) { System.out.
	 * println("The URL of zkHost is not correct!! Its form must as below:\n zkHost:port"
	 * ); e.printStackTrace(); } }
	 * 
	 * return solrServer; }
	 */
}
